package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result typeList() {
        //1.查询是否存在分类缓存
        List<String> types = stringRedisTemplate.opsForList().range("shopType", 0, -1);

        //2.有，则直接读取并返回
        if(types != null && !types.isEmpty()){
            List<ShopType> list = new ArrayList<>(types.size());

            for (String typeJson : types) {
                ShopType shopType = JSONUtil.toBean(typeJson, ShopType.class);
                list.add(shopType);
            }

            return Result.ok(list);
        }

        //3.没有，查询数据库
        List<ShopType> list = query().orderByAsc("sort").list();

        //4.建立redis缓存
        for (ShopType shopType : list) {
            //转JSON并存入
            stringRedisTemplate.opsForList().rightPush("shopType",JSONUtil.toJsonStr(shopType));
        }

        // 可以设置缓存过期时间，避免数据长期不一致
        stringRedisTemplate.expire("shopType", 1, TimeUnit.DAYS);

        return Result.ok(list);
    }
}
